﻿namespace LxCore
{
    public class ResidualMonitorCenter : JsObject
    {
        public ResidualMonitor Continuity { get; set; } = new("连续性", zf => zf.MassFlux);
        public ResidualMonitor Vel_U { get; set; } = new("动量U", zf => zf.Velocity?.U);
        public ResidualMonitor Vel_V { get; set; } = new("动量V", zf => zf.Velocity?.V);
        public ResidualMonitor Vel_W { get; set; } = new("动量W", zf => zf.Velocity?.W);
        public ResidualMonitor Temperature { get; set; } = new("温度", zf => zf.Temperature);
        public ResidualMonitor Turb_k { get; set; } = new("湍动能", zf => throw new NotImplementedException());
        public ResidualMonitor Turb_omega { get; set; } = new("比耗散率", zf => throw new NotImplementedException());
        public JsList<ResidualMonitor> ActiveResidualMonitors { get; set; } = new();
        public void CheckCreate()
        {
            ActiveResidualMonitors.Clear();
            checkAdd(Continuity);
            checkAdd(Vel_U);
            checkAdd(Vel_V);
            checkAdd(Vel_W);
            checkAdd(Temperature);
            //checkAdd(Turb_k);
            //checkAdd(Turb_omega);
            void checkAdd(ResidualMonitor rm)
            {
                rm.CheckCreate();
                if (!rm.IsEmpty)
                {
                    ActiveResidualMonitors.Add(rm);
                }
                else
                {
                    rm.ClearHistory();
                }
            }
        }
        public override void FromJsonKV(string key, IJsonReader jsReader)
        {
            switch (key)
            {
                case nameof(Continuity): jsReader.ReadObject(Continuity); break;
                case nameof(Vel_U): jsReader.ReadObject(Vel_U); break;
                case nameof(Vel_V): jsReader.ReadObject(Vel_V); break;
                case nameof(Vel_W): jsReader.ReadObject(Vel_W); break;
                case nameof(Temperature): jsReader.ReadObject(Temperature); break;
                default: base.FromJsonKV(key, jsReader); break;
            }
        }
        public override void ToJsonKV(IJsonWriter jsWriter)
        {
            base.ToJsonKV(jsWriter);
            writeResM(nameof(Continuity), Continuity);
            writeResM(nameof(Vel_U), Vel_U);
            writeResM(nameof(Vel_V), Vel_V);
            writeResM(nameof(Vel_W), Vel_W);
            writeResM(nameof(Temperature), Temperature);
            void writeResM(string name, ResidualMonitor m)
            {
                if (m.HistoryData != null && m.HistoryData.Count > 0)
                {
                    jsWriter.WriteObject(name, m);
                }
            }
        }
    }
}